package com.alcj.controller;

import com.alcj.common.base.BaseController;
import com.alcj.common.constant.SysConstant;
import com.alcj.common.utils.CmnUtil;
import com.alcj.common.utils.VerifyCodeUtil;
import com.alcj.common.vcode.Captcha;
import com.alcj.common.vcode.GifCaptcha;
import com.alcj.common.vcode.JpgCaptcha;
import com.alcj.model.LawNous;
import com.alcj.model.News;
import com.alcj.model.SiteShow;
import com.alcj.model.User;
import com.alcj.service.LawNousService;
import com.alcj.service.NewsService;
import com.alcj.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.Session;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 * @author :chenxh
 * @version :v1.0
 * @Package :com.alcj.controller
 * @Description :(首页管理)
 * @date :
 */
@Controller
@RequestMapping("/index")
public class IndexController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    NewsService newsService;

    @Autowired
    UserService userService;

    @Value("${web.upload-path}")
    private String uploadPath;

    @Autowired
    LawNousService lawNousService;

    /**
     * @Author: chenxh
     * @Description:
     * @Date: 2017/9/7 16:13
     * @param: request
     * @param: model
     */
    @RequestMapping("/home")
    public String getHomeInfo(HttpServletRequest request, Model model) {
        try {
            // 选择城市
            String selCity = (String) request.getSession().getAttribute("city");
            // 获取行业资讯
            List<News> industryList = newsService.getNewsInfo("0");

            // 获取公司新闻
            List<News> newsList = newsService.getNewsInfo("1");

            // 获取法律法规
            List<LawNous> lawList = lawNousService.getLawNousList("0");

            // 获取检测常识
            List<LawNous> nousList = lawNousService.getLawNousList("1");

            // 获取站点展示
            List<SiteShow> siteShowList = lawNousService.getSiteShowList(selCity);

            model.addAttribute("industryList", industryList);
            model.addAttribute("newsList", newsList);
            model.addAttribute("lawList", lawList);
            model.addAttribute("nousList", nousList);
            model.addAttribute("siteShowList", siteShowList);

        } catch (Exception e) {
            // 异常报错
            logger.error("获取首页信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }

        return "index";
    }

    /**
     * 获取动态手机验证码
     *
     * @param request
     * @return String
     */
    @RequestMapping("/getVerifyCode")
    @ResponseBody
    public String getVerifyCode(HttpServletRequest request,HttpServletResponse response) {
        try {
            String codeType = (String) request.getParameter("codeType");
            String resultData = "";
            if (codeType.equals("1")) {
                // 生成静态验证码
                resultData = VerifyCodeUtil.CreateJpgCode(uploadPath, request.getSession());
            } else if (codeType.equals("2")) {
                // 生成动态验证码

                resultData = VerifyCodeUtil.CreateGifCode(uploadPath, request.getSession());
            } else if (codeType.equals("3")) {
                // 生成手机验证码
                String goalPhone = (String) request.getParameter("goalPhone");
                if (!CmnUtil.isEmpty(goalPhone)) {
                    resultData = VerifyCodeUtil.CreatePhoneCode(goalPhone);
                }
                if (!CmnUtil.isEmpty(resultData)) {
                    request.getSession().setAttribute("phoneVerifyCode", resultData);
                }
            }
            return resultData;
        } catch (Exception e) {
            // 异常报错
            logger.error("获取动态验证码异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return "";
        }
    }

    /**
     * 获取静态验证码
     *
     * @param request
     * @return String
     */
    @RequestMapping("/getVerify")
    public void getVerify(HttpServletRequest request,HttpServletResponse response) {
        try {

            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");

            //生成随机字串
            String verifyCode = JpgCaptcha.generateVerifyCode(4);
            //存入会话session
            HttpSession session = request.getSession(true);
            session.setAttribute("verifyCode", verifyCode.toLowerCase());
            //生成图片
            VerifyCodeUtil.outputImage(response.getOutputStream(), verifyCode);
        } catch (Exception e) {
            // 异常报错
            logger.error("获取动态验证码异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
        }
    }

    /**
     * @param request
     * @return boolean
     * @Title: verificationCode
     * @Description:校验手机验证码是否正确
     */
    @RequestMapping("verificationCode")
    @ResponseBody
    public boolean verificationCode(HttpServletRequest request) {
        try {
            //获取session中的验证码
            String checkPhoneVerifyCode = (String) request.getParameter("verifyCode");
            String codeType = (String) request.getParameter("codeType");
            boolean isSuccess = false;
            //获取session中的验证码
            String verifyCode = "";
            //判断验证码类型
            if (codeType.equals("1") || codeType.equals("2")) {
                // 动态验证码
                verifyCode = (String) request.getSession().getAttribute("verifyCode");
            } else if (codeType.equals("3")) {
                // 手机验证码
                verifyCode = (String) request.getSession().getAttribute("phoneVerifyCode");
            }
            //判断手机验证码是否为空
            if (CmnUtil.isEmpty(checkPhoneVerifyCode) || CmnUtil.isEmpty(verifyCode)) {
                return isSuccess;
            } else {
                //比对验证码
                if (checkPhoneVerifyCode.toLowerCase().equals(verifyCode)) {
                    isSuccess = true;
                }
                return isSuccess;
            }
        } catch (Exception e) {
            // 异常报错
            logger.error("校验验证码异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return false;
        }
    }

    /**
     * @param request
     * @return boolean
     * @Title:
     * @Description:校验用户或者手机号是否存在
     */
    @RequestMapping("verifyBeing")
    @ResponseBody
    public boolean verifyBeing(HttpServletRequest request) {
        try {
            //获取验证类型
            String tagItem = (String) request.getParameter("tagItem");
            boolean isSuccess = false;

            //判断验证类型
            if (!CmnUtil.isEmpty(tagItem)) {
                isSuccess = userService.checkUserExist(tagItem);
            }

            return isSuccess;
        } catch (Exception e) {
            // 异常报错
            logger.error("校验验证码异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return false;
        }
    }

    /**
     * @Author: chenxh
     * @Description: 注册
     * @Date: 2017/9/7 16:13
     * @param: request
     * @param: model
     */
    @RequestMapping("/register")
    public String register(HttpServletRequest request, Model model) {
        try {
        } catch (Exception e) {
            // 异常报错
            logger.error("获取首页信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }

        return "register";
    }

    /**
     * @Author: chenxh
     * @Description:
     * @Date: 2017/9/7 16:13
     * @param: request
     * @param: model
     */
    @RequestMapping("/newsInfo")
    public String getNewsInfo(HttpServletRequest request, Model model) {
        try {

        } catch (Exception e) {
            // 异常报错
            logger.error("获取新闻资讯信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }

        return "newsInfo";
    }

    /**
     * @Author: chenxh
     * @Description:
     * @Date: 2017/9/7 16:13
     * @param: request
     * @param: model
     */
    @RequestMapping("/infoDetail")
    public String getInfoDetail(HttpServletRequest request, Model model) {
        try {

        } catch (Exception e) {
            // 异常报错
            logger.error("获取资讯详细信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }

        return "infoDetail";
    }
}
